package com.lsl.bhllserver.controller;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.lsl.bhllserver.entity.*;
import com.lsl.bhllserver.entity.userabstract.User;
import com.lsl.bhllserver.service.user.LoginService;
import com.lsl.bhllserver.service.user.RegisterService;
import com.lsl.bhllserver.service.user.UserManageService;

@RestController
public class UserController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private RegisterService registerService;

    @Autowired
    private UserManageService userManageService;

    @RequestMapping(path = "/bhll/api/login", method = RequestMethod.POST)
    public LoginResponse login(@RequestBody Map<String, String> data) {
        // System.out.println(data.get("userid") + " " + data.get("password") + " " +
        // data.get("role"));
        boolean flagLogin = loginService.logincheck(data.get("userid"), data.get("password"), data.get("role"));
        // String userid = "123";
        // String userRole = "admin";
        // return new LoginResponse(userid, userRole);
        if (flagLogin) {
            return new LoginResponse(data.get("userid"), data.get("role"));
        } else {
            return new LoginResponse("0", null);
        }
    }

    @RequestMapping(path = "/bhll/api/register", method = RequestMethod.POST)
    public RegisterResponse register(@RequestBody Map<String, String> data) {
        // System.out.println(data.get("username") + " " + data.get("password") + " " +
        // data.get("role"));
        Integer newUserId = registerService.register(
            data.get("username"), 
            data.get("password"), 
            data.get("role"),
            data.get("phone")
        );
        if (newUserId != 0) {
            return new RegisterResponse("success", newUserId);
        } else {
            return new RegisterResponse("fail", 0);
        }
    }

    @RequestMapping(path = "/bhll/api/account/get", method = RequestMethod.POST)
    // 新增 accountGet API，用于获取用户信息
    public AccountGetResponse accountGet(@RequestBody Map<String, String> data) {
        // System.out.println(data.get("userid") + " " + data.get("password") + " " +
        // data.get("role"));
        System.out.println(data.get("userid") + " " + data.get("role"));
        //User usertemp = userManageService.findUser(data.get("userid"), data.get("role"));
        if (data.get("role").equals("admin")) {
            Admin admintemp = (Admin) userManageService.findUser(data.get("userid"), "admin");
            return new AccountGetResponse(admintemp.getId(), admintemp.getAdminName(), admintemp.getAdminPassword(),
                    "admin", "", "", "");
        } else if (data.get("role").equals("business")) {
            Business businesstemp = (Business) userManageService.findUser(data.get("userid"), "business");
            return new AccountGetResponse(businesstemp.getId(), businesstemp.getBusName(),
                    businesstemp.getBusPassword(), "business", businesstemp.getBusPhone(), businesstemp.getBusAddress(),
                    businesstemp.getBusCaption());
        } else if (data.get("role").equals("customer")) {
            Customer customertemp = (Customer) userManageService.findUser(data.get("userid"), "customer");
            return new AccountGetResponse(customertemp.getId(), customertemp.getCusName(),
                    customertemp.getCusPassword(), "customer", customertemp.getCusPhone(), customertemp.getCusAddress(),
                    "");
        } else {
            System.out.println("角色不对！！！");
            return new AccountGetResponse(0, null, null, null, null, null, null);
        }
    }

    @RequestMapping(path = "/bhll/api/account/edit", method = RequestMethod.POST)
    public BoolResponse accountEdit(@RequestBody Map<String, String> data) {
        //System.out.println(data.get("userid") + " " + data.get("password") + " " + data.get("role"));
        User usertemp = userManageService.findUser(data.get("userid"), data.get("role"));
        boolean flag = userManageService.editUser(() -> {
            if (data.get("role").equals("customer")) {
                return new Customer(
                        Integer.parseInt(data.get("userid")),
                        data.get("username"),
                        ((Customer)usertemp).getCusPassword(),
                        data.get("phone"),
                        data.get("address"));
            } else if (data.get("role").equals("business")) {
                return new Business(
                        Integer.parseInt(data.get("userid")),
                        data.get("username"),
                        ((Business)usertemp).getBusPassword(),
                        data.get("phone"),
                        data.get("address"),
                        data.get("caption"));
            } else if (data.get("role").equals("admin")) {
                return new Admin(Integer.parseInt(
                        data.get("userid")),
                        data.get("username"),
                        data.get("password"));
            } else {
                return null;
            }
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/account/changePwd", method = RequestMethod.POST)
    public BoolResponse accountChangePwd(@RequestBody Map<String, String> data) {
        // TODO: 修改密码
        boolean flag = false;
        User usertemp = userManageService.findUser(data.get("userid"), data.get("role"));
        if (data.get("role").equals("customer")) {
            Customer custemp = (Customer) usertemp;
            if(!data.get("oldpassword").equals(custemp.getCusPassword())) {
                return new BoolResponse("incorrect");
            }
            flag = userManageService.editUser(() -> {
                Customer editTemp = new Customer();
                editTemp.setId(Integer.parseInt(data.get("userid")));
                editTemp.setCusPassword(data.get("newpassword"));
                return editTemp;
            });
        } else if (data.get("role").equals("business")) {
            Business bustemp = (Business) usertemp;
            if(!data.get("oldpassword").equals(bustemp.getBusPassword())) {
                return new BoolResponse("incorrect");
            }
            flag = userManageService.editUser(() -> {
                Business editTemp = new Business();
                editTemp.setId(Integer.parseInt(data.get("userid")));
                editTemp.setBusPassword(data.get("newpassword"));
                return editTemp;
            });
        } else {
            System.out.println("角色不对！！！");
            return new BoolResponse("fail");
        }
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    // 新增方法：删除账户
    @RequestMapping(path = "/bhll/api/account/delete", method = RequestMethod.POST)
    public BoolResponse accountDelete(@RequestBody Map<String, String> data) {
        boolean flag = userManageService.deleteUser(() -> {
            if (data.get("role").equals("customer")) {
                Customer obj = new Customer();
                obj.setId(Integer.parseInt(data.get("userid")));
                return obj;
            } else if (data.get("role").equals("business")) {
                Business obj = new Business();
                obj.setId(Integer.parseInt(data.get("userid")));
                return obj;
            } else {
                return null;
            }
        });
        if (flag) {
            return new BoolResponse("success");
        } else {
            return new BoolResponse("fail");
        }
    }

    @RequestMapping(path = "/bhll/api/account/list/customer", method = RequestMethod.GET)
    public Object customerList() {
        return userManageService.getAllUser("customer");
    }

    @RequestMapping(path = "/bhll/api/account/list/business", method = RequestMethod.GET)
    public Object businessList() {
        return userManageService.getAllUser("business");
    }

    @RequestMapping(path = "/bhll/api/account/search", method = RequestMethod.POST)
    public Object accountSearch(@RequestBody Map<String, String> data) {
        // TODO: 搜索用户
        String[] keywords = new String[] { 
            data.get("userid").isBlank() ? "" : data.get("userid"),
            data.get("username").isBlank() ? "" : data.get("username"),
            data.get("phone").isBlank() ? "" : data.get("phone"),
            data.get("address").isBlank() ? "" :data.get("userid"),
        };
        return userManageService.searchUser(keywords, data.get("role"));
    }

    /*
     * =============================================================================
     * =============
     */

    /*
     * 内部类：用于返回登录验证结果
     */
    class LoginResponse {
        private String userid;
        private String role;

        public LoginResponse(String userid, String role) {
            this.userid = userid;
            this.role = role;
        }

        public String getUserid() {
            return userid;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }
    }

    /*
     * 内部类：用于返回 Customer 列表
     */
    // class CustomerListResponse {
    // private Customer[] customers;

    // public CustomerListResponse(Customer[] customers) {
    // this.customers = customers;
    // }

    // public public void setCustomers(Customer[] customers) {
    // this.customers = customers;
    // }

    // public Customer[] getCustomers() {
    // return customers;
    // }
    // }

    /*
     * 内部类：用于 Boolean 型结果
     */
    class BoolResponse {
        private String flag;

        public BoolResponse(String flag) {
            this.flag = flag;
        }

        public String getFlag() {
            return flag;
        }

        public void setFlag(String flag) {
            this.flag = flag;
        }

    }

    /*
     * 内部类：用于返回 AccountGet 结果
     */
    class AccountGetResponse {
        private Integer userid;
        private String username;
        private String password;
        private String role;
        private String phone;
        private String address;
        private String caption;

        public AccountGetResponse(Integer userid, String username, String password, String role, String phone,
                String address, String caption) {
            this.userid = userid;
            this.username = username;
            this.password = password;
            this.role = role;
            this.phone = phone;
            this.address = address;
            this.caption = caption;
        }

        public Integer getUserid() {
            return userid;
        }

        public void setUserid(Integer userid) {
            this.userid = userid;
        }

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getPhone() {
            return phone;
        }

        public void setPhone(String phone) {
            this.phone = phone;
        }

        public String getAddress() {
            return address;
        }

        public void setAddress(String address) {
            this.address = address;
        }

        public String getCaption() {
            return caption;
        }

        public void setCaption(String caption) {
            this.caption = caption;
        }
    }

    /*
     * 内部类：用于返回账户注册响应信息
     */
    class RegisterResponse {
        private String flag;
        private Integer userid;

        public RegisterResponse(String flag, Integer userid) {
            this.flag = flag;
            this.userid = userid;
        }

        public String getFlag() {
            return flag;
        }

        public void setFlag(String flag) {
            this.flag = flag;
        }

        public Integer getUserid() {
            return userid;
        }

        public void setUserid(Integer userid) {
            this.userid = userid;
        }
    }
}
